package com.xsoft.web.util;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xsoft.web.Exception.FileProcessException;



public class FileProcessUtil {
	 // 循环读取文件时，允许读取的最大字节数
    /** The Constant BUFFER_SIZE. */
    private static final int BUFFER_SIZE = 16 * 1024;
    private static final Logger logger = LoggerFactory.getLogger(FileProcessUtil.class);
    /**
     * 如果是BMP图片，自动转换为JPG格式
     */
    public String saveFileAndBmpToJpg(File file, String fileName, String fileUrl) throws FileProcessException {
    	String extName = FileUtil.getExtension(fileName);
    	extName = extName.equalsIgnoreCase("bmp")?"jpg":extName;
    	return saveFile(file, fileName, fileUrl, extName);
    }
    
    /**
     * @see com.ztgame.module.file.FileProcess#saveFile(java.io.File, java.lang.String)
     */
    public String saveFile(File file, String fileName, String fileUrl) throws FileProcessException {
    	return saveFile(file, fileName, fileUrl, FileUtil.getExtension(fileName));
    }
    
    /**
     * @see com.ztgame.module.file.FileProcess#saveFile(java.io.File, java.lang.String)
     */
    public String saveFile(File file, String fileName, String fileUrl, String newExtensionName) throws FileProcessException {
        InputStream in = null;
        OutputStream out = null;
        boolean hasDir = true;
        // 如果文件夹不存在，程序生成
        hasDir = FileUtil.createDir(fileUrl, true);

        if (hasDir) {
            String newName = "";
            if(newExtensionName != null && !"".equals(newExtensionName)) {
            	newName = fileName + "." + newExtensionName;
            }else {
            	newName = fileName;
            }
            logger.info("保存文件：" + newName);
            File newFile = new File(fileUrl + newName);
            FileUtil.deleteFile(newFile);
            try {
                // 对内容不为空的文件进行上传处理
                if (file.length() > 0) {
                    in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
                    out = new BufferedOutputStream(new FileOutputStream(newFile), BUFFER_SIZE);
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int size = 0;
                    while ((size = in.read(buffer)) > 0) {
                        if (size > BUFFER_SIZE)
                            out.write(buffer);
                        else
                            out.write(buffer, 0, size);
                    }
                }
            } catch (IOException e) {
            	e.printStackTrace();
                throw new FileProcessException("生成文件出错");
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        throw new FileProcessException("生成文件出错");
                    }
                }
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        throw new FileProcessException("生成文件出错");
                    }
                }
            }
            return newName;
        }
        return null;
    }

    /**
     * @see com.ztgame.module.file.FileProcess#saveFile(java.util.List, java.util.List,
     *      java.util.List)
     */
    public List<String> saveFile(List<File> files, List<String> fileName, String fileUrl)
            throws FileProcessException {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see com.ztgame.module.image.ImageProcess#deleteImage(java.lang.String)
     */
    public void deleteFile(String url) throws FileProcessException {
        FileUtil.deleteFile(new File(url));
    }

    /**
     * @see com.ztgame.module.image.ImageProcess#deleteImageList(java.util.List)
     */
    public void deleteFileList(List<String> urls) throws FileProcessException {
        for (String url : urls) {
            FileUtil.deleteFile(new File(url));
        }
    }

    /**
     * @see com.ztgame.module.file.FileProcess#saveFile(javax.servlet.ServletInputStream,
     *      java.lang.String)
     */
    public String saveFile(InputStream stream, String fileUrl) throws FileProcessException {
        InputStream in = null;
        OutputStream out = null;
        boolean hasDir = true;
        // 如果文件夹不存在，程序生成
        hasDir = FileUtil.createDir(fileUrl, true);

        if (hasDir) {
            String newName = IDHexGenerator.generateID() + ".jpg";
            File newFile = new File(fileUrl + newName);
            try {
                in = new BufferedInputStream(stream, BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(newFile), BUFFER_SIZE);
                byte[] buffer = new byte[BUFFER_SIZE];
                int size = 0;
                while ((size = in.read(buffer)) > 0) {
                    if (size > BUFFER_SIZE)
                        out.write(buffer);
                    else
                        out.write(buffer, 0, size);
                }
            } catch (IOException e) {
                throw new FileProcessException("");
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        throw new FileProcessException("");
                    }
                }
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        throw new FileProcessException("");
                    }
                }
            }
            return newName;
        }
        return null;
    }
}
